package replica;

import java.net.SocketException;
import java.net.UnknownHostException;

import udp.UdpClient;
import udp.message.FailMessage;
import util.ConfigurationHelper;
import client.CommandClient;

public class FailureClient extends CommandClient {
	
	public FailureClient() {
		super();
	}

	public void sendFailure(String replicaID, String failure) {
		
		FailMessage fail = new FailMessage(failure);
		
		UdpClient RMtoReplica = null;
		
		try {
			String host = ConfigurationHelper.getProperty(replicaID+".replica.host");
			int port =  ConfigurationHelper.getIntProperty(replicaID + ".replica.port");
			System.out.println("Sending message to " + host + ":" + port);
			RMtoReplica = new UdpClient(host, port);
		} catch (SocketException | UnknownHostException e) {
			System.out.println("Could not create client to send failure message: " +e.getMessage());
			e.printStackTrace();
		} 
		
		RMtoReplica.send(fail);
		
	}
	

	
	public void run() {
		showHeader("Replica Manager Failure Console");
		
		while (true) {
			int choice = promptMenu("Failure Type", "Select an option", "Software Failure", "Crash Failure");
			
			int replica = promptMenu("Replica", "Select a replica", "R1", "R2", "R3", "R4");
			
			String failure = "none";
			if (choice == 1) failure = "software";
			else if (choice == 2) failure = "crash";
			
			System.out.println("Causing a *" + failure + " failure* on replica R" + replica);
			System.out.println();
			
			String replicaID = "r" + replica;
			
			sendFailure(replicaID, failure);
			
			System.out.println();
			System.out.println("Done.");
			waitForEnter();
			
		}
	}
	
	public static void main(String[] args) {
		
		FailureClient client = new FailureClient();
		
		client.run();
		
		
	}
}
